package cn.sciento.iam.saas.domain.service.observer;

import javax.annotation.Nonnull;

import cn.sciento.core.ldap.DirectoryType;
import org.apache.commons.lang3.StringUtils;
import cn.sciento.iam.domain.entity.Ldap;
import cn.sciento.iam.domain.entity.Tenant;
import cn.sciento.iam.domain.repository.LdapRepository;
import cn.sciento.iam.saas.domain.service.TenantObserver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.Assert;

public class TenantLdapObserver implements TenantObserver<Ldap> {
  private static final Logger LOGGER = LoggerFactory.getLogger(TenantLdapObserver.class);
  
  @Autowired
  private LdapRepository ldapRepository;
  
  @Value("${stong.iam.default-ldap-password:test}")
  private String defaultLdapPassword;
  
  @Override
  public int order() {
    return 40;
  }
  
  @Override
  public Ldap tenantCreate(@Nonnull Tenant tenant) {
    Ldap ldap = generateDefaultLdap(tenant);
    ldap.createValidate();
    this.ldapRepository.insertSelective(ldap);
    LOGGER.info("[TenantInit - Num={}] -> {}", tenant.getTenantNum(), ldap);
    return ldap;
  }
  
  @Override
  public Ldap tenantUpdate(@Nonnull Tenant tenant) {
    Ldap ldap = this.ldapRepository.selectLdapByTenantId(tenant.getTenantId());
    Assert.notNull(ldap, "error.data_not_exists");
    if (!StringUtils.equals(ldap.getName(), tenant.getTenantName())) {
      ldap.setName(tenant.getTenantName());
      this.ldapRepository.updateOptional(ldap, "name");
      LOGGER.info("Update tenant ldap, tenantNum is [{}], ldap is {}", tenant.getTenantNum(), ldap);
    } 
    return ldap;
  }
  
  protected Ldap generateDefaultLdap(Tenant tenant) {
    Ldap ldap = new Ldap();
    ldap.setOrganizationId(tenant.getTenantId());
    ldap.setName(tenant.getTenantName());
    ldap.setServerAddress("127.0.0.1");
    ldap.setPort("389");
    ldap.setDirectoryType(DirectoryType.OPEN_LDAP.value());
    ldap.setEnabled(Boolean.TRUE);
    ldap.setUseSSL(Boolean.FALSE);
    ldap.setObjectClass("person");
    ldap.setSagaBatchSize(500);
    ldap.setConnectionTimeout(10);
    ldap.setAccount("test");
    ldap.setLdapPassword(this.defaultLdapPassword);
    ldap.setUuidField("entryUUID");
    ldap.setLoginNameField("uid");
    ldap.setEmailField("mail");
    return ldap;
  }
}
